package com.qfedu.controller;

import com.qfedu.utils.FileUtil;
import com.qfedu.utils.VerifyCodeUtil;
import com.qfedu.vo.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;

@Controller
@RequestMapping("/api/image/")
public class ImageController {
    @RequestMapping("createcode.do")
    public void createImg(HttpServletResponse response, HttpSession session) throws IOException {
        //1.生成对应宽高的初始图片
        BufferedImage verifyImg=new BufferedImage(200,50,BufferedImage.TYPE_INT_RGB);
        //2.单独的一个类方法，出于代码复用考虑，进行了封装。功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
        String randomText = VerifyCodeUtil.drawRandomText(200,50,verifyImg);
        //3.服务端记录验证码
        session.setAttribute("code", randomText);
        System.err.println(randomText);
        //4.必须设置响应内容类型为图片，否则前台不识别
        response.setContentType("image/png");
        //5.写出图片
        ImageIO.write(verifyImg,"png",response.getOutputStream());
    }

    //上传图片，返回访问路径
    /**
     * 图片上传
     * 1.post请求
     * 2.参数*/
    @PostMapping("uploadimg.do")
    @ResponseBody
    public R uploadImg(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.验证是否存在
        if(!file.isEmpty()){

            //2.获取上传的文件名，重命名并限制长度
            String fn= FileUtil.rename(file.getOriginalFilename());
            //3.获取并创建真实路径的文件夹
            File dir=new File(request.getServletContext().getRealPath("/upload"));
            if(!dir.exists()){
                dir.mkdirs();
            }

            //4.IO流 实现内容的保存  生成 字节流
            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File(dir,fn)));
            bos.write(file.getBytes());
            bos.close();

            //5.返回访问路径
            return R.ok("/upload/"+fn);
        }
        return R.fail();
    }
}
